package com.mojo.concurrent.concurrent_06_future;

import java.util.Random;
import java.util.concurrent.*;

/**
 * Future体系API示例
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class FutureDemo01 {
    public static void main(String[] args) {
        FutureExecutorService();
    }

    private static void FutureExecutorService() {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Future<Integer> future = executorService.submit(() -> {
            Thread.sleep(3000L);
            return new Random(1).nextInt(500);
        });
        System.out.println("idDone():" + future.isDone());
        //阻塞等待
        //noTimeOut(future);

        //超时等待
        //timeOut(future);
        executorService.shutdown();
    }

    private static void timeOut(Future<Integer> future) {
        try {
            System.out.println("get() timeout:" + future.get(500, TimeUnit.MICROSECONDS));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void noTimeOut(Future<Integer> future) {
        try {
            System.out.println("get():" + future.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
